<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AppUser } from '#/api/platform/appuser';

import { Page } from '@vben/common-ui';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { changeStatus, listUser } from '#/api/platform/appuser';

import { columnsSchema, querySchema } from './data';

const formOptions: VbenFormProps = {
  collapsed: true, // 默认展开
  schema: querySchema(), // 查询参数
  showCollapseButton: false, // 控制表单是否显示折叠按钮
  submitOnEnter: false, // 按下回车时是否提交表单
};

const [Grid] = useVbenVxeGrid({
  formOptions,
  gridEvents: {},
  gridOptions: {
    columns: columnsSchema(onStatusChange),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await listUser({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
    },
    treeConfig: {
      transform: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function onStatusChange(newStatus: string, row: AppUser) {
  const status: Recordable<string> = {
    '1': '禁用',
    '0': '启用',
  };
  return ElMessageBox.confirm(
    `是否将状态切换为 【${status[newStatus.toString()]}】 吗？`,
    `切换状态`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await changeStatus(row.userId, newStatus);
      return true;
    })
    .catch(() => {
      return false;
    });
}
</script>

<template>
  <Page auto-content-height>
    <Grid />
  </Page>
</template>
